import { OnInit, OnChanges, OnDestroy, Component, ChangeDetectionStrategy, ViewEncapsulation, Input, TemplateRef, NgZone, ViewChild, ElementRef } from '@angular/core';
import { InputNumber, InputBoolean } from 'ng-zorro-antd';
import { Lbchart } from '@shared';
import { Subscription } from 'rxjs';
/**
 * 基础漏斗图
 */
@Component({
  selector: 'lb-basic-funnel',
  template: `
  <div #basicfunnel></div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush, // 检测改为按需，即不自动刷新
})
export class LbBasicFunnelComponent implements OnInit, OnChanges, OnDestroy,Lbchart {
  private chart: any;
  private resize$: Subscription;
  @ViewChild('basicfunnel', { static: true }) private node: ElementRef;
  @Input() padding: Array<number | string> | string = 'auto';
  @Input() @InputNumber() delay = 0;
  @Input() color:string[] = null;
  @Input() colorFiled='name';
  @Input() position: any

  // @Input() position: {x: string, y: string} = {x: 'action', y: 'pv'}

  @Input() data: any [] 

  @Input() width: number;
  @Input() height: number;

  @Input() datasort = 'DESC' // 排序规则，升序或降序
  @Input() @InputBoolean() tooltipshow = true;
  @Input() @InputBoolean() tooltipshowpercent = true;
  @Input() @InputBoolean() tooltipshowtitle = false

  @Input() legendposition;
  @Input() legendlayout;
  @Input() @InputBoolean() legendshow = true;
  @Input() @InputBoolean() legendshowpercent = true;

  @Input() @InputBoolean() labelshow = false;

  @Input() sortx = true
  @Input() sortz
  @Input() sortrule = 'ASC'


  constructor(private ngZone: NgZone) { }

  commonStyleHandle(chart, data) {
    const dv = new DataSet.View().source(data)

    // if(this.sortx && !this.sortz) {
    //   dv.transform({
    //     type: 'sort-by',
    //     fields: [ this.sortx ], // 根据指定的字段集进行排序，与lodash的sortBy行为一致
    //     order: this.sortrule,        // 默认为 ASC，DESC 则为逆序
    //   })
    // } else if(!this.sortx && this.sortz){
    //   dv.transform({
    //     type: 'sort-by',
    //     fields: [ this.sortz ], // 根据指定的字段集进行排序，与lodash的sortBy行为一致
    //     order: this.sortrule,   // 默认为 ASC，DESC 则为逆序
    //   })
    // } else if(this.sortx && this.sortz) {
    //   dv.transform({
    //     type: 'sort-by',
    //     fields: [ this.sortx, this.sortz ], // 根据指定的字段集进行排序，与lodash的sortBy行为一致
    //     order: this.sortrule,   // 默认为 ASC，DESC 则为逆序
    //   })
    // }    

    dv.transform({
      type: 'percent',
      field: this.position.y, // 统计销量
      dimension: this.position.x, // 每年的占比
      // groupBy: [ 'category' ], // 以不同产品类别为分组，每个分组内部各自统计占比
      as: 'percent', // 结果存储在 percent 字段
    });
    dv.transform({
      type: 'sort-by',
      fields: [this.position.y],
      order: this.datasort,
    })
    chart.source(dv.rows)

    // 无坐标轴
     chart.axis(false);

     
    // 图例
    if (this.legendshow) {
      chart.legend(this.position.x, {
        position: this.legendposition,
        layout: this.legendlayout,
        itemFormatter: val => {
          return (
            val.toString() +
            (this.legendshowpercent
              ? ' (' +
                Math.round(
                  dv.rows.find(ele => ele[this.position.x] === val).percent *
                    10000,
                ) /
                  100 +
                '%)'
              : '')
          );
        },
      });
    } else {
      chart.legend(false);
    }

      // 工具提示
      if (this.tooltipshow) {
        chart.tooltip({
          showTitle: this.tooltipshowtitle,
          itemTpl: '<li data-index={index} style="margin-bottom:4px;">'
        + '<span style="background-color:{color};" class="g2-tooltip-marker"></span>'
        + '<span style="padding-left: 16px">{name}: {value}'+ (this.tooltipshowpercent? ' ({percent}%)': '') + '</span><br/>'
        + '</li>'
        });
      } else {
        chart.tooltip(false);
      }

    return dv.rows
  }

  install() {
    this.render()
  }

  render() {
    const { node, padding } = this;
    const container = node.nativeElement as HTMLElement;

    const chart = (this.chart = new G2.Chart({
      container,
      forceFit: true,  // 图表的宽度自适应开关
      height: this.getHeight(),
      padding,
    }));

    this.commonStyleHandle(chart, this.data)
  
   
    chart.coord('rect').transpose().scale(1, -1);
    chart.intervalSymmetric()
      .position(`${this.position.x}*${this.position.y}`)
      .shape('funnel')
      .color(this.position.x)
      .label(`${this.position.x}*${this.position.y}`, (action, pv) => {
        if(!this.labelshow) return 
        return action + ' ' + pv;
      }, {
        offset: -10,
        labelLine: {
          lineWidth: 0.9,
          stroke: 'rgba(255, 255, 255, 0.75)'
        }
      })
      .tooltip(
        `${this.position.x}*${this.position.y}*percent`,
        (x, y, percent) => {
          return {
            name: x,
            value: y,
            percent: Math.round(percent * 10000) / 100,
          };
        },
      );
    
    // Step 4: 渲染图表
    chart.render();

    // this.attachChart();
  }

   attachChart() {
    const { chart, padding, data, color } = this;
    if (!chart || !data || data.length <= 0) return;
    const height = this.getHeight();
    if (chart.get('height') !== height) {
      chart.changeHeight(height);
    }
    const dvrows = this.commonStyleHandle(chart, this.data)
     // color
    //  chart.get('geoms')[0].color(this.colorFiled,this.color);
     chart.set('padding', padding);
     chart.changeData(dvrows);
  }

  destroy(){
    if (this.resize$) {
      this.resize$.unsubscribe();
    }
    if (this.chart) {
      this.ngZone.runOutsideAngular(() => this.chart.destroy());
    }
  }

  /**
   * 报表高度
   * 存在报表头，则需要减掉报表头的高度
   */
   getHeight() {
     return this.height
    // return this.title ? (this.height - TITLE_HEIGHT) : this.height;
  }


  ngOnInit(): void {
    if(this.position&&this.data.length>0){
      this.ngZone.runOutsideAngular(() => setTimeout(() => this.install(), this.delay));
    }
   
  }  
  
  ngOnChanges(changes: import("@angular/core").SimpleChanges): void {
    this.ngZone.runOutsideAngular(() => this.attachChart());
  }
  ngOnDestroy(): void {
    this.destroy();
  }
}